package com.skcc.cip.ngms;

import java.io.InputStream;

import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.After;
import org.junit.Before;
import org.springframework.context.support.AbstractApplicationContext;

import com.meterware.httpunit.HttpNotFoundException;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.servletunit.ServletRunner;
import com.meterware.servletunit.ServletUnitClient;

public class ServletRouterTestSupport extends CamelTestSupport {
	public static final String CONTEXT = "/mycontext";
	public static final String CONTEXT_URL = "http://localhost/mycontext";
	protected ServletRunner sr;
	protected boolean startCamelContext = true;
	protected AbstractApplicationContext applicationContext;

	@Before
	public void setUp() throws Exception {
		InputStream is = this.getClass().getResourceAsStream(getConfiguration());
		assertNotNull("The configuration input stream should not be null", is);
		sr = new ServletRunner(is, CONTEXT);

		loadServlets();

		HttpUnitOptions.setExceptionsThrownOnErrorStatus(true);
		if (startCamelContext) {        
			super.setUp();
		}
	}

	@After
	public void tearDown() throws Exception {
		if (startCamelContext) {
			super.tearDown();
		}
		sr.shutDown();
	}

	protected void loadServlets() throws Exception {
		try {
			sr.newClient().getResponse(CONTEXT_URL + "/services");
		} catch (HttpNotFoundException e) {
			// ignore, we just want to boot up the servlet
		} 
	}

	/**
	 * @return The web.xml to use for testing.
	 */
	protected String getConfiguration() {
		return "/web.xml";
	}

	protected ServletUnitClient newClient() {
		return sr.newClient();
	}

}
